package com.cash.loan.modular.cash.controller;

import com.cash.loan.core.upload.QiniuService;
import com.cash.loan.modular.cash.result.ServerResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @Date 2018-07-12 8:29
 */
@Controller
@RequestMapping(value = "/cash")
@Api(description = "图片上传")
public class UploadController {

    @Autowired
    private QiniuService qiniuService;

    /**
     * 图片上传
     * @param picture
     * @return
     * @throws IOException
     * @throws
     */
    @ApiOperation("用户头像上传")
    @PostMapping(value = "/upload")
    @ResponseBody
    public ServerResponse updatePicture(@RequestPart("picture") MultipartFile picture) throws IOException {
        String filenameExtension = picture.getOriginalFilename().substring(picture.getOriginalFilename().lastIndexOf("."), picture.getOriginalFilename().length());
        InputStream content = picture.getInputStream();
        String pictureAddr = qiniuService.upload(filenameExtension,content);
        Map<String,String> result = new HashMap<>();
        result.put("pictureUrl",pictureAddr);
        return ServerResponse.getSuccess("update success",result);
    }

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     * @throws
     */
    @ApiOperation("供element上传插件使用")
    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public ServerResponse updateFile(@RequestPart("file") MultipartFile file) throws IOException {
        String filenameExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
        InputStream content = file.getInputStream();
        String pictureAddr = qiniuService.upload(filenameExtension,content);
        Map<String,String> result = new HashMap<>();
        result.put("pictureUrl",pictureAddr);
        return ServerResponse.getSuccess("success",result);
    }
}
